package com.yt.lxh.product.config;

import com.yt.lxh.constant.MQConst;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.*;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * 产品售卖状态更新的通知配置
 */
@Slf4j
@Configuration
public class SaleNotifyConfig implements ApplicationContextAware {

    // 声明交换机，且持久化
    @Bean(MQConst.GOODS_DIRECT_EXCHANGE)
    public DirectExchange productSaleStatusUpdateExchange() {
        // 3个参数：交换机名称，是否持久化，没有队列绑定是否自动删除
        return new DirectExchange(MQConst.GOODS_DIRECT_EXCHANGE, true, false);
    }

    // 产品销售状态上架队列，且持久化
    @Bean(MQConst.GOODS_UPPER_QUEUE)
    public Queue goodsUpperQueue() {
        return QueueBuilder.durable(MQConst.GOODS_UPPER_QUEUE).build();
    }

    // 产品销售状态下架队列，且持久化
    @Bean(MQConst.GOODS_LOWER_QUEUE)
    public Queue goodsLowerQueue() {
        return QueueBuilder.durable(MQConst.GOODS_LOWER_QUEUE).build();
    }

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        // 获取 RabbitTemplate
        RabbitTemplate rabbitTemplate = applicationContext.getBean(RabbitTemplate.class);
        // 设置 ReturnCallBack
        rabbitTemplate.setReturnCallback((message, replyCode, replyText, exchange, routingKey) -> {
            log.info("【RabbitMQ】消息发送失败 ---> 应答码：{}，原因：{}，交换机：{}，路由键：{}，消息：{}",
                    replyCode, replyText, exchange, routingKey, message);
        });
    }
}
